//
//  LiangpinDetailViewController.m
//  HomeIn
//
//  Created by dllo on 15/11/7.
//  Copyright © 2015年 ZZP. All rights reserved.
//

#import "LiangpinDetailViewController.h"
#import "LiangpinModel.h"
#import "LiangpinOfIntroduceCell.h"
#import "LiangpinOfCommentCell.h"
#import "CommentModel.h"
#import "LiangpinDetailModel.h"
#import "StringWithHeight.h"

@interface LiangpinDetailViewController ()<SDCycleScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, retain) UITableView *tableView;

@property (nonatomic, retain) NSMutableArray *modelArray;
@property (nonatomic, retain) NSMutableArray *commentModelArray;


@property (nonatomic, retain) UIButton *introduceButton;
@property (nonatomic, retain) UIButton *CommentButton;

@property (nonatomic, retain) UIView *headerView;
@property (nonatomic, retain) UIView *introduceView;
@property (nonatomic, retain) UILabel *titleLabel;
@property (nonatomic, retain) UILabel *priceLabel;
@property (nonatomic, retain) UILabel *descriptionLabel;

@property (nonatomic, assign) BOOL isSelected;

@end

@implementation LiangpinDetailViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //视图将要出现的时候刷新
    [self.tableView reloadData];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.modelArray = [NSMutableArray array];
    self.commentModelArray = [NSMutableArray array];
    
    //默认为图文介绍
    self.isSelected = YES;
    
    //导航栏标题
    self.navigationItem.title = @"商品详情";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    //导航栏左侧按钮
    UIImage *image = [UIImage imageNamed:@"iconfont-unie642.png"];
    //取消渲染
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(leftBarAction)];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64)  style:UITableViewStylePlain];
    self.tableView.backgroundColor = RGBA(236, 235, 241, 1);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
    
    //取消cell线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //头部
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 2 + HEIGHT / 3)];
    self.headerView.backgroundColor = RGBA(247, 247, 247, 1);
    self.tableView.tableHeaderView = self.headerView;
    
    if (self.liangpinModel.image_urls.count == 1) {
        
        UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 2)];
        [imageview sd_setImageWithURL:[NSURL URLWithString:[self.liangpinModel.image_urls objectAtIndex:0]]];
        [self.headerView addSubview:imageview];
    } else {
        
        //轮播图
        SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 2) imageURLStringsGroup:nil];
        // 设置pageControl居右，默认居中
        cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
        cycleScrollView.delegate = self;
        //图片数组
        cycleScrollView.imageURLStringsGroup = self.liangpinModel.image_urls;
        // 自定义轮播时间间隔
        cycleScrollView.autoScrollTimeInterval = 2.0;
        [self.headerView addSubview:cycleScrollView];

    }
    
    //介绍
    self.introduceView = [[UIView alloc] initWithFrame:CGRectMake(0, HEIGHT / 2 , WIDTH, HEIGHT / 3 )];
    self.introduceView.backgroundColor = [UIColor whiteColor];
    [self.headerView addSubview:self.introduceView];
    
    //标题
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, WIDTH - 10 * 2, self.introduceView.frame.size.height / 5)] ;
    self.titleLabel.text = self.liangpinModel.name;
    self.titleLabel.textAlignment = NSTextAlignmentLeft;
    self.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:20];
    [self.introduceView addSubview:self.titleLabel];
    
    //价钱
    self.priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.titleLabel.frame.origin.x, self.titleLabel.frame.origin.y + self.titleLabel.frame.size.height, self.titleLabel.frame.size.width, self.titleLabel.frame.size.height / 2)];
    self.priceLabel.text = [NSString stringWithFormat:@" %@ 元",self.liangpinModel.price];
    self.priceLabel.textAlignment = NSTextAlignmentLeft;
    self.priceLabel.textColor = [UIColor redColor];
    self.priceLabel.font = [UIFont systemFontOfSize:20];
    [self.introduceView addSubview:self.priceLabel];
    
    //描述
    self.descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.priceLabel.frame.origin.x, self.priceLabel.frame.origin.y + self.priceLabel.frame.size.height + 10, self.priceLabel.frame.size.width, self.priceLabel.frame.size.height * 3)];
    self.descriptionLabel.text = self.liangpinModel.descriptions;
    self.descriptionLabel.font = [UIFont systemFontOfSize:17];
    self.descriptionLabel.textAlignment = NSTextAlignmentLeft;
    self.descriptionLabel.textColor = [UIColor grayColor];
    self.descriptionLabel.lineBreakMode = NSLineBreakByWordWrapping;
    self.descriptionLabel.numberOfLines = 0;
    [self.descriptionLabel sizeToFit];
    [self.introduceView addSubview:self.descriptionLabel];
    
    //调用方法计算内容高度
    CGFloat height = [StringWithHeight HeightWithText:self.descriptionLabel.text width:self.descriptionLabel.frame.size.width font:self.descriptionLabel.font];
    
    //height是CGFloat类型;frame是CGRect类型
    CGRect frame = self.descriptionLabel.frame;
    frame.size.height = height;
    self.descriptionLabel.frame = frame;
    
    //介绍view自适应高度
    CGRect frameOfIntroduceView = self.introduceView.frame;
    frameOfIntroduceView.size.height = self.descriptionLabel.frame.origin.y + height + 10;//+ 10与底部空出点地方
    self.introduceView.frame = CGRectMake(0, HEIGHT / 2, WIDTH, frameOfIntroduceView.size.height);
    //头部自适应高度
    CGRect frameOfHeaderView = self.headerView.frame;
    frameOfHeaderView.size.height = HEIGHT / 2 + self.introduceView.frame.size.height;
    self.headerView.frame = CGRectMake(0, 0, WIDTH, frameOfHeaderView.size.height);
    //注意, 要重新给头视图赋值
    self.tableView.tableHeaderView = self.headerView;

    
    [self getAFNetWorkingData:self.liangpinModel.id];//图文介绍数据
    [self getAFNetWorkingDataForComment:self.liangpinModel.id];//评论数据
    
}

//请求数据
-(void)getAFNetWorkingData:(NSInteger)ids
{
    
    //接⼝
    NSString *urlString = [NSString stringWithFormat:@"http://api.bohejiaju.com/v2/items/%ld", self.liangpinModel.id];
    
    //[NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];  代表支持所有的接口类型
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSMutableDictionary *dictionary = responseObject;
        
        NSMutableDictionary *dic = [dictionary objectForKey:@"data"];
        
        LiangpinDetailModel *liangpinDetailModel = [[LiangpinDetailModel alloc] init];
        [liangpinDetailModel setValuesForKeysWithDictionary:dic];
        liangpinDetailModel.descriptions = [dic objectForKey:@"description"];
        
        [self.modelArray addObject:liangpinDetailModel];
        
        //刷新
        [self.tableView reloadData];
        
    }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             
             NSLog(@"error = %@",error);
         }];
    
}

- (void)getAFNetWorkingDataForComment:(NSInteger)ids
{
    NSString *urlString = [NSString stringWithFormat:@"http://api.bohejiaju.com/v2/items/%ld/comments?limit=20&offset=0", ids];
    
    //[NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];  代表支持所有的接口类型
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSMutableDictionary *dictionary = responseObject;
        NSMutableArray *array = [[dictionary objectForKey:@"data"] objectForKey:@"comments"];
        
        for (NSMutableDictionary *dic in array)
        {
            CommentModel *commentModel = [[CommentModel alloc] init];
            [commentModel setValuesForKeysWithDictionary:dic];
            
            [self.commentModelArray addObject:commentModel];
            
        }

        [self.tableView reloadData];
        
    }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             
             NSLog(@"error = %@",error);
         }];
}



//指定分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//区头视图 会悬停
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 15)];
    
    //图文介绍
    self.introduceButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.introduceButton.frame = CGRectMake(0, 0, WIDTH / 2, myView.frame.size.height);
    self.introduceButton.backgroundColor = [UIColor yellowColor];
    [self.introduceButton setTitle:@"图文介绍" forState:UIControlStateNormal];
    [self.introduceButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.introduceButton addTarget:self action:@selector(introduceButton:) forControlEvents:UIControlEventTouchUpInside];
    [myView addSubview:self.introduceButton];
    
    
    //灰线
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(WIDTH / 2, 0, 1, myView.frame.size.height)];
    lineView.backgroundColor = [UIColor blackColor];
    [myView addSubview:lineView];
    
    //攻略
    self.CommentButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.CommentButton.frame = CGRectMake(WIDTH / 2 + 1, 0, WIDTH / 2 - 1, myView.frame.size.height);
    self.CommentButton.backgroundColor = [UIColor yellowColor ];
    [self.CommentButton setTitle:@"评论" forState:UIControlStateNormal];
    [self.CommentButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.CommentButton addTarget:self action:@selector(CommentButton:) forControlEvents:UIControlEventTouchUpInside];
    [myView addSubview:self.CommentButton];
    
    
    return myView;
}

//区头视图高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return HEIGHT / 15;
}


//指定多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.isSelected == YES)
    {
        return self.modelArray.count;
    }
    else
    {
        return self.commentModelArray.count;
    }
    
}


//创建一个cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isSelected == YES)
    {
        //创建自定义cell
        static NSString *cellIndentifier = @"Cell";
        LiangpinOfIntroduceCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
        if (cell == nil)
        {
            cell = [[LiangpinOfIntroduceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;//设置cell点击效果 (没有置灰效果)
        
        LiangpinDetailModel *liangpinDetailModel = [self.modelArray objectAtIndex:indexPath.row];
        cell.liangpinDetailModel = liangpinDetailModel;
        
        return cell;
    }
    else
    {
        //创建自定义cell
        static NSString *cellIndentifier = @"cell";
        LiangpinOfCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
        if (cell == nil)
        {
            cell = [[LiangpinOfCommentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        }
        
        //恢复cell线
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        //设置cell点击效果 (没有置灰效果)
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        CommentModel *commentModel = [self.commentModelArray objectAtIndex:indexPath.row];
        cell.commentModel = commentModel;
        return cell;
    }
    
    
}

//图文介绍
- (void)introduceButton:(UIButton *)button
{
    self.isSelected = YES;
    [self.tableView reloadData];
}

//评论
- (void)CommentButton:(UIButton *)button
{
    self.isSelected = NO;
    [self.tableView reloadData];
}



//设置行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isSelected == YES)
    {
        return HEIGHT;
    }
    else
    {
        return  HEIGHT / 6;
    }
    
}

//- (void)rightBarAction:(UIButton *)buttton
//{
//    
//    //搜索数据库中所有的礼物表
//    NSMutableArray *array = [[DataBaseHandle ShareDataBaseHandle] selectAllGiftTable];
//    
//    NSMutableArray *titleArray = [NSMutableArray array];
//    //在数据库返回的数组中,将model的名字循环添加到标题数组中
//    for (RecommendModel *recommendModel in array)
//    {
//        [titleArray addObject:recommendModel.name];
//    }
//    
//    //如果标题数组中不包含本页面的名字,则说明没有收藏过本页面
//    if (![titleArray containsObject:self.recommendModel.name])
//    {
//        [[DataBaseHandle ShareDataBaseHandle] createGiftTable];//创建收藏表
//        [[DataBaseHandle ShareDataBaseHandle] insertGiftTable:self.recommendModel];//将model插入表中
//        
//        
//        UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//        [alertV show];
//        [alertV release];
//    }
//    else
//    {
//        UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经被收藏过" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//        [alertV show];
//        [alertV release];
//        
//    }
//    
//}


- (void)leftBarAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
